package com.bugstack.domain.strategy.service.rule.tree.impl;

import com.bugstack.domain.strategy.model.vo.RuleLogicCheckTypeVO;
import com.bugstack.domain.strategy.model.vo.StrategyAwardStockKeyVO;
import com.bugstack.domain.strategy.repository.IStrategyRepository;
import com.bugstack.domain.strategy.service.armory.IStrategyDispatch;
import com.bugstack.domain.strategy.service.rule.tree.ILogicTree;
import com.bugstack.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author: czb
 * @Description: 扣除仓储规则树节点
 * @DateTime: 2025/3/10 16:04
 **/
@Slf4j
@Component("rule_stock")
public class RuleStockTreeNode implements ILogicTree {

    @Resource
    private IStrategyDispatch strategyDispatch;

    @Resource
    private IStrategyRepository strategyRepository;

    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date endDateTime) {
        log.info("规则过滤-库存扣减 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
        //1.尝试扣除库存
        boolean status = strategyDispatch.subtractionAwardStock(strategyId, awardId, endDateTime);
        //扣除成功 true
        if (status) {
            log.info("规则过滤-库存扣减-成功 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
            //2.往延时队列中发送消息
            strategyRepository.awardStockConsumeSendQueue(StrategyAwardStockKeyVO.builder().
                    awardId(awardId).
                    strategyId(strategyId).build());
            //3.返回结果
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .strategyAwardVO(
                            DefaultTreeFactory.StrategyAwardVO.builder()
                                    .awardRuleValue(ruleValue)
                                    .awardId(awardId)
                                    .build()
                    )
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                    .build();
        }
        log.info("规则过滤-库存扣减-失败 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
        //扣除失败
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                .build();
    }
}
